package com.x.utils;

import java.net.URLDecoder;
import java.net.URLEncoder;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;

import jodd.http.HttpRequest;
import jodd.http.HttpResponse;

/**
 * <p>
 * Description:手机号码工具
 * </p>
 * 
 * @Author Chenkangming
 * @Date 2015年11月6日
 * @version 1.0
 */
public class MobileUtil {
	private static Logger log = LoggerFactory.getLogger("api");

	/**
	 * 
	 * 执行手机号码查询
	 * 
	 * 
	 * 
	 * @param mobile
	 * 
	 * @return {mobile,province,city,isp,card}
	 * 
	 */
	public static JSONObject getMobileInfo(String mobile) {
		JSONObject info = null;
		try {
			if (info == null) {
				info = baiduForMobile(mobile, "http://apis.baidu.com/apistore/mobilenumber/mobilenumber?phone=", "api.mobile.baidu.apikey");
			}
			if (info == null) {
				info = kvgoForMobile(mobile, "http://sj.kvgo.net/?type=json&number=");
			}
			if (info == null) {
				info = ip138ForMobile(mobile, "http://www.ip138.com:8080/search.asp?action=mobile&mobile=");
			}
		} catch (Exception e) {
			log.error("查询手机号码归属地异常{}", e);
		}

		return info;
	}

	/**
	 * 
	 * 百度接口
	 * 
	 * 
	 * 
	 * @param mobile
	 * 
	 *            手机号码
	 * 
	 * @param url
	 * 
	 *            url请求地址
	 * 
	 * @param apikey
	 * 
	 *            apikey
	 * 
	 * @return {mobile,province,city,isp,card}
	 * 
	 */
	private static JSONObject baiduForMobile(String mobile, String url, String apikey) {
		// 百度

		try {
			HttpRequest httpRequest = HttpRequest.get(url + mobile);
			httpRequest.header("apikey", apikey);
			HttpResponse response = httpRequest.send();
			String result = response.bodyText();
			JSONObject json = JSONObject.parseObject(result);
			if (json.getInteger("errNum") != 0) {
				log.error("百度手机号码返回异常{}", json);
				return null;
			} else {
				JSONObject retData = json.getJSONObject("retData");
				JSONObject info = new JSONObject();
				info.put("mobile", mobile);
				info.put("province", retData.get("province"));
				info.put("city", retData.get("city"));
				String card = retData.getString("supplier");
				String isp = "未知";
				if (card.contains("移动")) {
					isp = "中国移动";
				} else if (card.contains("电信")) {
					isp = "中国电信";
				} else if (card.contains("联通")) {
					isp = "中国联通";
				} else {
					isp = card;
				}
				info.put("isp", isp);
				info.put("card", retData.get("suit"));
				return info;
			}
		} catch (Exception e) {
			log.error("百度手机号码归属地解析异常{}", e);
		}
		return null;
	}

	/**
	 * 
	 * 通过http://sj.kvgo.net/?type=json&number= 接口查询手机号码
	 * 
	 * 
	 * 
	 * @param mobile
	 * 
	 * @return {mobile,province,city,isp,card}
	 * 
	 */
	private static JSONObject kvgoForMobile(String mobile, String _url) {
		JSONObject info = new JSONObject();
		String url = _url.concat(mobile);
		try {
			Document doc = Jsoup.connect(url).get();
			String result = doc.text();
			log.info(result);
			JSONObject json = JSONObject.parseObject(result);
			info.put("mobile", mobile);
			info.put("province", json.get("province"));
			info.put("city", json.get("city"));
			String card = json.getString("card");
			String isp = "未知";
			if (card.contains("移动")) {
				isp = "中国移动";
			} else if (card.contains("电信")) {
				isp = "中国电信";
			} else if (card.contains("联通")) {
				isp = "中国联通";
			} else {
				isp = card;
			}
			info.put("isp", isp);
			info.put("card", card);
			if (StringUtil.isEmpty(info.getString("card"))) {
				info = null;
				log.error("kvgo接口查询异常 {}" + result);
			}
		} catch (Exception e) {
			log.error(url + "访问异常：" + e);
			info = null;
		}
		return info;
	}

	/**
	 * 
	 * 通过IP138查询
	 * 
	 * 
	 * 
	 * @param mobile
	 * 
	 * @return {mobile,province,city,isp,card}
	 * 
	 */
	private static JSONObject ip138ForMobile(String mobile, String _url) {
		JSONObject info = new JSONObject();
		try {
			String url = _url + mobile;

			HttpRequest httpRequest = HttpRequest.get(url);
			
			HttpResponse response = httpRequest.send().charset("gb2312");
			System.out.println(response.getHttpRequest());
			String result = response.bodyText();
			result = URLEncoder.encode(result, "utf-8");
			result = URLDecoder.decode(result, "utf-8");

			Document doc = Jsoup.parse(result);
			Element table = doc.select("table").last();

			Elements trs = table.select("tr");
			info.put("mobile", mobile);
			for (int i = 2; i < trs.size(); i++) {
				Elements tds = trs.get(i).select("td");
				String str = tds.get(1).text().trim();
				str = CharMatcher.WHITESPACE.collapseFrom(str, ' ');
				Splitter split = Splitter.on(" ").trimResults().omitEmptyStrings();// 用逗号分割且去掉每个字符串周围的空格

				Iterable<String> res = split.split(str);

				int j = 0;
				for (String s : res) {
					if (i == 2) {
						if (j == 0) {
							info.put("province", s);
						} else if (j == 1) {
							info.put("city", s);
						}
						j++;
					} else if (i == 3) {
						info.put("card", s);
						if (s.contains("移动")) {
							info.put("isp", "中国移动");
						} else if (s.contains("电信")) {
							info.put("isp", "中国电信");
						} else if (s.contains("联通")) {
							info.put("isp", "中国联通");
						} else {
							info.put("isp", s);
						}
					} else if (i == 4) {
					} else if (i == 5) {
						if (j == 0) {
						}
						j++;
					}
				}
			}
			if (StringUtil.isEmpty(info.getString("isp"))) {
				info = null;
				log.error("IP138查询异常>>>：" + table.html());
			}
		} catch (Exception e) {
			log.error("IP138查询号码归属地异常{}" + e);
			info = null;
		}
		if (info != null) {
			log.info(info.toString());
			if (info.getString("isp").equals("未知")) {
				info = null;
			}
		}
		return info;
	}

	public static void main(String[] args) {
		System.out.println(ip138ForMobile("18923852099", "http://www.ip138.com:8080/search.asp?action=mobile&mobile="));
//		System.out.println(kvgoForMobile("18923852099", "http://sj.kvgo.net/?type=json&number="));
	}
}
